<template>
  <div class="favorite-list-page">
    <HeaderNav />
    
    <div class="container">
      <div class="page-header">
        <h1 class="page-title">我的收藏</h1>
        <div class="header-actions">
          <el-button
            type="danger"
            :disabled="selectedProducts.length === 0"
            @click="batchRemove"
          >
            批量取消收藏
          </el-button>
          <el-button
            type="danger"
            plain
            :disabled="productList.length === 0"
            @click="clearAll"
          >
            清空收藏
          </el-button>
        </div>
      </div>

      <div class="favorite-list" v-loading="loading">
        <div v-if="productList.length > 0" class="product-grid">
          <div
            v-for="product in productList"
            :key="product.id"
            class="favorite-item"
          >
            <el-checkbox
              v-model="selectedProducts"
              :label="product.id"
              class="item-checkbox"
            />
            <ProductCard
              :product="product"
              :in-favorite-list="true"
              :initial-favorite="true"
              @remove="handleRemoveFavorite"
              @favorite-changed="handleFavoriteChanged"
            />
          </div>
        </div>

        <el-empty
          v-if="!loading && productList.length === 0"
          description="暂无收藏商品"
        />
      </div>

      <!-- 分页 -->
      <el-pagination
        v-if="total > 0"
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :total="total"
        :page-sizes="[12, 24, 48]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        class="pagination"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import HeaderNav from '@/components/HeaderNav.vue'
import ProductCard from '@/components/ProductCard.vue'
import { getFavoriteList, removeFromFavorite, batchRemoveFavorites, clearAllFavorites } from '@/api/favorite'

const loading = ref(false)
const productList = ref([])
const selectedProducts = ref([])
const total = ref(0)

const pagination = reactive({
  current: 1,
  size: 24
})

// 加载收藏列表
const loadFavorites = async () => {
  loading.value = true
  try {
    const res = await getFavoriteList({
      current: pagination.current,
      size: pagination.size
    })
    if (res.code === 200 && res.data) {
      productList.value = res.data.records || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.message || '加载收藏列表失败')
    }
  } catch (error) {
    console.error('加载收藏列表失败:', error)
    ElMessage.error('加载收藏列表失败')
  } finally {
    loading.value = false
  }
}

// 处理收藏移除事件
const handleRemoveFavorite = (productId) => {
  // 从列表中移除该商品
  productList.value = productList.value.filter(p => p.id !== productId)
  // 从选中列表中移除
  selectedProducts.value = selectedProducts.value.filter(id => id !== productId)
  // 更新总数
  total.value = Math.max(0, total.value - 1)
}

// 处理收藏状态变化
const handleFavoriteChanged = (isFavorited) => {
  // 如果取消收藏，不需要额外处理，因为ProductCard已经触发了remove事件
  if (!isFavorited) {
    // 状态变化由handleRemoveFavorite处理
    return
  }
}

// 取消收藏（用于批量操作等场景）
const removeFavorite = async (productId) => {
  try {
    const res = await removeFromFavorite(productId)
    if (res.code === 200) {
      ElMessage.success('取消收藏成功')
      handleRemoveFavorite(productId)
    } else {
      ElMessage.error(res.message || '取消收藏失败')
    }
  } catch (error) {
    console.error('取消收藏失败:', error)
    ElMessage.error('取消收藏失败')
  }
}

// 批量取消收藏
const batchRemove = async () => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请选择要取消收藏的商品')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要取消收藏这 ${selectedProducts.value.length} 件商品吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 调用批量删除API
    const res = await batchRemoveFavorites(selectedProducts.value)
    if (res.code === 200) {
      ElMessage.success('批量取消收藏成功')
      // 从列表中移除选中的商品
      const selectedIds = new Set(selectedProducts.value)
      productList.value = productList.value.filter(p => !selectedIds.has(p.id))
      total.value = Math.max(0, total.value - selectedProducts.value.length)
      selectedProducts.value = []
    } else {
      ElMessage.error(res.message || '批量取消收藏失败')
      return
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量取消收藏失败:', error)
      ElMessage.error('批量取消收藏失败')
    }
  }
}

// 清空收藏
const clearAll = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清空所有收藏吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 调用清空API
    const res = await clearAllFavorites()
    if (res.code === 200) {
      ElMessage.success('清空收藏成功')
    } else {
      ElMessage.error(res.message || '清空收藏失败')
      return
    }
    
    selectedProducts.value = []
    loadFavorites()
  } catch (error) {
    // 用户取消
  }
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadFavorites()
}

// 页码改变
const handlePageChange = (page) => {
  pagination.current = page
  loadFavorites()
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

onMounted(() => {
  loadFavorites()
})
</script>

<style lang="scss" scoped>
.favorite-list-page {
  min-height: 100vh;
  background-color: #f5f7fa;

  .container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
  }

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: white;
    padding: 20px 30px;
    border-radius: 8px;
    margin-bottom: 20px;

    .page-title {
      font-size: 24px;
      margin: 0;
    }

    .header-actions {
      display: flex;
      gap: 15px;
    }
  }

  .favorite-list {
    .product-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
      gap: 20px;
    }

    .favorite-item {
      position: relative;
      background: white;
      border-radius: 8px;
      padding: 10px;

      .item-checkbox {
        position: absolute;
        top: 15px;
        left: 15px;
        z-index: 10;
        background: rgba(255, 255, 255, 0.9);
        padding: 5px;
        border-radius: 4px;
      }
    }
  }

  .pagination {
    display: flex;
    justify-content: center;
    padding: 20px;
    background: white;
    border-radius: 8px;
    margin-top: 20px;
  }
}
</style>

